//
//  SerialPostTagView.m
//  XPhoto
//
//  Created by sentinel on 2020/4/10.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "SerialPostTagView.h"
#import "UIScrollView+x.h"
#import "PostTag.h"

@interface SerialPostTagView()
@property(nonatomic, strong) NSMutableDictionary *cachedTableView;
@end

@implementation SerialPostTagView
- (void)removeTableViewObserve{
    if (_cachedTableView) {        
        for (UITableView *tableView in _cachedTableView.allValues) {
            [tableView removeObserver:self forKeyPath:@"contentSize" context:nil];
        }
    }
}
- (void)initAfterAwakeFromNib{
    if (!_cachedTableView) {
        _cachedTableView = [NSMutableDictionary dictionary];
    }
}
- (UITableView *)tableViewAtIndex:(NSInteger)index{
    NSString *key = [NSString stringWithFormat:@"%ld", index];
    UITableView *tableView = [self.cachedTableView valueForKey:key];
    return tableView;
}
- (void)cacheTableView:(UITableView *)tableView atIndex:(NSInteger)index{
    NSString *key = [NSString stringWithFormat:@"%ld", index];
    if (![self tableViewAtIndex:index]) {
        [self.cachedTableView setValue:tableView forKey:key];
    }
}

- (void)reload{
    [self layoutSerialGroupView];
    SysDictItem *dictItem = [SysDict itemForValue:[@(SERIAL_TYPE_TAG) description] dictKey:SYS_DICT_SERIAL_TYPE_KEY];
    self.serialGroupView.title = dictItem?dictItem.title:nil;
    self.serialGroupView.selectedIndex = 0;
    
    [self prepareTableViewAtIndex:self.serialGroupView.selectedIndex];
    [self searchTags];
}
- (void)prepareTableViewAtIndex:(NSInteger)index{
    @synchronized (self.cachedTableView) {
        UITableView *tableView = [self tableViewAtIndex:index];
        CGRect frame = self.contentScrollView.bounds;
        frame.origin.x = self.contentScrollView.bounds.size.width * index;
        if (!tableView) {
            tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
            tableView.tableFooterView = [UIView new];
            tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            tableView.delegate = self;
            tableView.dataSource = self;
            [tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
            tableView.backgroundColor = [UIColor clearColor];
            [self.contentScrollView addSubview:tableView];
            [self cacheTableView:tableView atIndex:index];
        }
        CGSize contentSize = self.contentScrollView.bounds.size;
        contentSize.width = MAX(contentSize.width, frame.origin.x + frame.size.width);
        [self.contentScrollView setContentOffset:frame.origin animated:YES];
        self.tableView = tableView;
    }
}
- (void)searchTags{
    [PostSerial searchTagsWithSerialId:self.postSerial.id
                          withCallback:^(id task, NSArray *tags, NSError * error) {
        if (error) {
            [BKIndicator showMessage:error.localizedDescription duration:3.0f completion:nil];
            return;
        }
        if (!tags || tags.count == 0) {
            [BKIndicator showMessage:NSLocalizedString(@"not_found_tag_for_serial", nil) duration:3.0f completion:nil];
            [self.actionDelegate serialTypeViewDidNotSupportCurrentSerialType:self];
            return;
        }
        if (tags && tags.count > 0) {
            NSMutableArray *grps = [NSMutableArray array];
            for (NSInteger i = 0, n = [tags count]; i < n; i++) {
                PostTag *tag = [tags objectAtIndex:i];
                Group *grp = [Group new];
                grp.title = tag.title;
                grp.id = [@(tag.id) description];
                [grps addObject:grp];
            }
            self.groups = grps;
            self.serialGroupView.items = self.groups;
            [self searchWithGroupIndex:0 postOffset:0];
        }
        
    }];
}
- (void)searchWithGroupIndex:(NSInteger)groupIndex postOffset:(NSInteger)offset{
    Group *grp = [self.groups objectAtIndex:groupIndex];
    PostSearchArgs *args = [PostSearchArgs new];
    args.serialId = [NSNumber numberWithLong:self.postSerial.id];
    args.tag = grp.title;
    args.offset = offset;
    args.pageSize = 20;
    
    [Post searchBySerialTagWithArgs:args
                     callback:^(id  _Nonnull task, id  _Nonnull photos, NSError * _Nonnull error) {
        if (error) {
            [BKIndicator showMessage:error.localizedDescription duration:3.0f completion:nil];
            return;
        }
        if ([photos count] > 0 ){
            if (offset == 0) {
                grp.data = [NSMutableArray arrayWithCapacity:[photos count]];
            }
            [grp.data addObjectsFromArray:photos];
            [[self tableViewAtIndex:groupIndex] reloadData];
        }
        [self.tableView stopRefreshing];
        [self.tableView stopLoading];
        BOOL loadMore = args.pageSize == [photos count];
        self.tableView.loadMore = loadMore;
    }];
}

#pragma UITableViewDelegate
- (Post *)postAtIndexPath:(NSIndexPath *)indexPath{
    Group *grp = [self.groups objectAtIndex:self.serialGroupView.selectedIndex];
    Post *post = [grp.data objectAtIndex:indexPath.row];
    return post;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    Group *grp = [self.groups objectAtIndex:self.serialGroupView.selectedIndex];
    NSInteger n = grp.data.count;
    return n;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    PhotoTableViewCell *cachedCell = [self photoTableViewCell];
//    Post *post = [self postAtIndexPath:indexPath];
//    
//    CGFloat h = [cachedCell cellHeightWithPost:post width:self.tableView.bounds.size.width];
//    return h;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Post *post = [self postAtIndexPath:indexPath];
    
    PhotoTableViewCell *cell = [self photoTableViewCell];
    cell.post = post;
    return cell;
}
#pragma SerialGroupViewDelegate
- (void)didClickedSerialGroupItemAtIndex:(NSInteger)index{
    [self prepareTableViewAtIndex:index];
    Group *grp = [self.groups objectAtIndex:index];
    if ( [grp.data count] == 0 ) {
        [self searchWithGroupIndex:index postOffset:0];
    }
}
@end
